package com.dex4d.ui.dapp;


import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.core.AppBaseFragment;
import com.dex4d.core.CustomApplication;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.ui.dapp.adapter.HistoryAdapter;
import com.dex4d.ui.dapp.model.History;
import com.dex4d.ui.dapp.model.TabDappEvent;
import com.framework.util.DisplayUtil;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;


public class HistoryFragment extends AppBaseFragment implements SwipeMenuCreator, SwipeMenuItemClickListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private int bookmark;
    private OnDappBookMarkListener mListener;


    public HistoryFragment() {
        // Required empty public constructor
    }

    @BindView(R.id.web_recycler)
    SwipeMenuRecyclerView web_recycler;

    @BindView(R.id.btn_delete)
    TextView btn_delete;

    HistoryAdapter adapter;

    public static HistoryFragment newInstance(String param1, int bookmark) {
        HistoryFragment fragment = new HistoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM2, bookmark);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            bookmark = getArguments().getInt(ARG_PARAM2, 0);
        }

        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_history;
    }

    @Override
    protected void initVariables() {

        web_recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        HorizontalDividerItemDecoration decoration =
                new HorizontalDividerItemDecoration
                        .Builder(getActivity())
                        .color(Color.TRANSPARENT)
                        .size(DisplayUtil.dip2px(getActivity(), 10))
                        .showLastDivider()
                        .build();
        web_recycler.addItemDecoration(decoration);

        adapter = new HistoryAdapter(getActivity(), bookmark);

        if (bookmark == 0) {
            web_recycler.setSwipeMenuCreator(this::onCreateMenu);
            web_recycler.setSwipeMenuItemClickListener(this::onItemClick);
        }

        web_recycler.setAdapter(adapter);
    }

    @Override
    protected void loadData() {

        Observable
                .create((Observable.OnSubscribe<List<History>>) subscriber -> {
                    List<History> list;
                    list = bookmark == 0 ? CustomApplication.getDb().browserDao().getAll() : CustomApplication.getDb().browserDao().getAll(bookmark);
                    if (list == null || list.isEmpty()) {
                        subscriber.onError(new Throwable("Empty"));
                    } else {
                        subscriber.onNext(list);
                        subscriber.onCompleted();
                    }
                })
                .compose(new DefaultTransformer<List<History>>())
                .subscribe(new ProgressSubscriber<List<History>>(getActivity(), true) {
                    @Override
                    public void onNext(List<History> result) {
                        adapter.addAll(result);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnDappBookMarkListener) {
            mListener = (OnDappBookMarkListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentDappListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void dappHistory(TabDappEvent event) {
        if (bookmark == 0) return;//历史记录不处理
        switch (event.flag) {
            case 0:
                adapter.showDeleteUI(event);
                btn_delete.setVisibility(View.VISIBLE);
                break;
            case 1:
                adapter.selectAll(event);
                btn_delete.setVisibility(View.VISIBLE);
                break;
            case 2:
                adapter.selectAll(event);
                btn_delete.setVisibility(View.VISIBLE);
                break;
            case 3:
                break;
            case 4://取消按钮
                btn_delete.setVisibility(View.GONE);
                adapter.hideDeleteUI(event);
                break;
            case 5://删除完毕
                btn_delete.setVisibility(View.GONE);
                mListener.reset();
                break;
            default:
                break;
        }
    }

    /**
     * 删除所选项目
     */
    @OnClick(R.id.btn_delete)
    public void delete() {
        adapter.confirmDelete();
    }

    @Override
    public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()).setBackground(R.drawable.selector_red)
//                .setImage(R.mipmap.ic_action_delete)
                .setText(getResources().getString(R.string.dapp_bookmark_delete))
                .setTextColor(Color.WHITE)
                .setWidth(DisplayUtil.dip2px(getActivity(), 100))
                .setHeight(height);
        rightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

    }

    @Override
    public void onItemClick(SwipeMenuBridge menuBridge, int position) {
        menuBridge.closeMenu();
        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
        if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
            Observable
                    .create(new Observable.OnSubscribe<History>() {
                        @Override
                        public void call(Subscriber<? super History> subscriber) {
                            History history=adapter.getItemData(position);
                            CustomApplication.getDb().browserDao().deleteItem(history);
                            subscriber.onNext(history);
                            subscriber.onCompleted();
                        }
                    })
                    .compose(new DefaultTransformer<History>())
                    .subscribe(new ProgressSubscriber<History>(getActivity(), true) {
                        @Override
                        public void onNext(History result) {
                            adapter.removeItem(position);
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }
                    });


        }

        else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {

        }
    }


    public interface OnDappBookMarkListener {
        void onDappHistory();

        void onDappBookmark();

        /**
         * 重置页面
         */
        void reset();
    }

}
